<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\GoodsOrder;
use App\Models\GoodsOrder as GoodsOrderModel;
use Darabonba\GatewaySpi\Models\InterceptorContext\request;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Support\Env;
use App\Admin\Actions\Grid\GoodsOrder\Logistics;
use Dcat\Admin\Widgets\Tab;
use App\Admin\Actions\Grid\GoodsOrder\CreateOrderCancel;
use App\Admin\Actions\Grid\GoodsOrder\CreateOrderDelivery;
use App\Admin\Actions\Grid\GoodsOrder\CreateOrderComplete;

class GoodsOrderController extends AdminController
{

    public function __construct()
    {
        $this->type = request()->type;
        if(empty($this->type)){
            $this->type = 2;
        }
        return $this;
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        //$tab = Tab::make();
        //$tab->add('选项卡1', view('...'), true);

        return Grid::make(new GoodsOrder(), function (Grid $grid) {

            $grid->header(function () {
                $tab = Tab::make();

                $tab->addLink('待支付', '?type=1',$this->type==1 ? true : false);
                $tab->addLink('待发货', '?type=2',$this->type==2 ? true : false);
                $tab->addLink('待收货', '?type=3',$this->type==3 ? true : false);
                $tab->addLink('已完成', '?type=4',$this->type==4 ? true : false);
                $tab->addLink('已取消', '?type=5',$this->type==5 ? true : false);

                return $tab;
            });

            switch ($this->type){
                case 1:
                    $grid->model()->with(['user'])->where('order_status','=',GoodsOrderModel::ORDER_UNPAID)->orderByDesc('id');
                    $grid = self::tabGrid($grid);
                    $grid->showRowSelector();
                    $grid->batchActions(function (Grid\Tools\BatchActions $actions) {
                        $actions->add(new CreateOrderCancel());
                    });


                    break;
                case 2:
                    $grid->model()->with(['user'])
                        ->where('order_status','=',GoodsOrderModel::ORDER_PAID)
                        ->orderByDesc('pay_time');
                    $grid = self::tabGrid($grid);
                    $grid->column('pay_time');
                    $grid->showRowSelector();
                    $grid->batchActions(function (Grid\Tools\BatchActions $actions) {
                        $actions->add(new CreateOrderDelivery());
                    });
                    break;
                case 3:
                    $grid->model()->with(['user'])
                        ->where('order_status','=',GoodsOrderModel::ORDER_NOT_RECEIVED)
                        ->orderByDesc('pay_time');
                    $grid = self::tabGrid($grid);
                    $grid->column('pay_time');
                    $grid->column('delivery_time');
                    $grid->showRowSelector();
                    $grid->batchActions(function (Grid\Tools\BatchActions $actions) {
                        $actions->add(new CreateOrderComplete());
                    });
                    break;
                case 4:
                    $grid->model()->with(['user'])
                        ->where('order_status','=',GoodsOrderModel::ORDER_END)
                        ->orderByDesc('id');
                    $grid = self::tabGrid($grid);
                    $grid->column('pay_time');
                    $grid->column('delivery_time');
                    $grid->column('complete_time');
                    break;
                case 5:
                    $grid->model()->with(['user'])
                        ->whereIn('order_status',[GoodsOrderModel::ORDER_CANCEL,GoodsOrderModel::ORDER_TIME_OUT_CANCEL])
                        ->orderByDesc('id');
                    $grid = self::tabGrid($grid);
                    break;

            }


        });
    }

    public function tabGrid($grid){
        $grid->column('id');
        $grid->column('order_sn')->display(function ($value) {
            if(in_array($this->order_status,[GoodsOrderModel::ORDER_NOT_RECEIVED,GoodsOrderModel::ORDER_END])){
                return '<a target="_blank" href="/admin/logistic?good_order_id='.$this->id.'">'.$value.'</a>';
            }else{
                return $value;
            }
        });
        $grid->column('user.tiktokno',trans('user.fields.tiktokno'))->display(function ($var){
            return $this->user_id."({$var})";
        });
        $grid->column('order_total_original_price')->display(function ($var)use(&$pagetotal) {
            return $var / 100;
        });
        $grid->column('order_total_price')->display(function ($var) {
            return $var / 100;
        });
        $grid->column('order_total_profit')->display(function ($var) {
            return $var / 100;
        });

        $grid->column('order_status')->display(function ($var){
            return GoodsOrderModel::ORDER_STATUS[$var];
        });
        $grid->column('created_at');
        $grid->column('add_time');



        $grid->header(function ($collection)use ($grid,$pagetotal) {
            $query = GoodsOrderModel::query();
            $query2 = GoodsOrderModel::query();
            $page = [];
            // 拿到表格筛选 where 条件数组进行遍历
            $grid->model()->getQueries()->unique()->each(function ($value) use (&$query,&$query2,&$page) {
                if (in_array($value['method'], ['paginate','get', 'orderBy', 'orderByDesc'], true)) {
                    if($value['method'] == 'paginate'){
                        $page = $value['arguments'];
                        $query2->offset($page[0] * ($page[3]-1))->limit($page[0]);
                    }
                    if($value['method'] == 'orderBy' || $value['method'] == 'orderByDesc'){
                        $query2 = call_user_func_array([$query2, $value['method']], $value['arguments'] ?? []);
                    }
                    return;
                }
                $query = call_user_func_array([$query, $value['method']], $value['arguments'] ?? []);
                $query2 = call_user_func_array([$query2, $value['method']], $value['arguments'] ?? []);

            });

            $datapage = $query2->get()->sum('order_total_original_price')/100;
            // 查出统计数据
            $data = $query->sum('order_total_original_price') / 100;

            return "<div style='padding: 10px;'>当前页总金额 ： $datapage     所有总金额 ： $data</div>";
        });

        $grid->quickSearch('order_sn','user.tiktokno','user.tiktokid','user_id');
        $grid->filter(function (Grid\Filter $filter) {
            $filter->equal('order_sn');
            $filter->like('user.id', trans('user.fields.id'));
            $filter->equal('user.tiktokno',trans('user.fields.tiktokno'));
            //$filter->equal('order_status')->select(GoodsOrderModel::ORDER_STATUS);
            $filter->between('created_at')->datetime();
            $filter->between('pay_time')->datetime();
        });
        $grid->batchActions(function (Grid\Tools\BatchActions $actions) {
            $actions->disableDelete();
        });
        $grid->disableDeleteButton();
        $grid->disableViewButton();
        $grid->disableCreateButton();
        $grid->disableRowSelector();
        $grid->disableActions();

        //$grid->paginate(3);

        return $grid;
    }



    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new GoodsOrder(), function (Show $show) {
            $show->field('id');
            $show->field('order_sn');
            $show->field('user_id');
            $show->field('order_status');
            $show->field('pay_time');
            $show->field('delivery_time');
            $show->field('order_create_type');
            $show->field('complete_time');
            $show->field('remark');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new GoodsOrder(), function (Form $form) {
            $form->display('id');
            $form->text('order_sn');
            $form->text('user_id');
            $form->text('order_status');
            $form->text('pay_time');
            $form->text('delivery_time');
            $form->text('order_create_type');
            $form->text('complete_time');
            $form->text('remark');

            $form->display('created_at');
            $form->display('updated_at');
        });
    }


    public function generalCreate(){
        if(Admin::user()->isAdministrator()) {
            $agent_id = 0;
        }else{
            $agent_id = Admin::user()->id;
        }


        $data = [
            'agent_id' => $agent_id,
            'api_url'  => config('app.url')
        ];
        return view('Admin.generalCreate', $data);
    }

    public function autoCreate(){
        if(Admin::user()->isAdministrator()) {
            $agent_id = 0;
        }else{
            $agent_id = Admin::user()->id;
        }


        $data = [
            'agent_id' => $agent_id
        ];
        return view('Admin.autoCreate', $data);
    }



}
